#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, Float, Boolean, String, Unicode, UnicodeText, \
    DateTime, UniqueConstraint
from controls.data_pool_mysql import engine

Session = sessionmaker()
Session.configure(bind=engine)

"""sight_img collection has
    sightid:         景点id（int）
    imgid:           图片id（int）
    index:           顺序（int, 从0开始）
"""

sight_img_table_dict = {}


class SigntImgTables(object):
    def make_table(self, p_cityid):
        if sight_img_table_dict.has_key(p_cityid):
            return sight_img_table_dict[p_cityid]

        class SigntImgItem(object):
            def __init__(self, p_cityid):
                self.cityid = p_cityid

            def to_dict(self):
                res = {}
                res['sightid'] = self.sightid
                res['imgid'] = self.imgid
                res['index'] = self.index
                return res

            def to_min_dict(self):
                res = {}
                res['index'] = self.index
                res['url'] = self.imgid
                return res

            def __repr__(self):
                return "%d" % (self.sightid)

        metadata = MetaData()
        sight_img_item_table = Table(
            'sight_img_' + str(p_cityid), metadata,
            Column('id', Integer, primary_key=True),
            Column('sightid', Integer, nullable=False),
            Column('index', Integer, nullable=False),
            Column('imgid', Integer, nullable=False),
            UniqueConstraint('sightid', 'index', name='uix_sightid_index')
        )
        mapper(SigntImgItem, sight_img_item_table)
        table = {
            'metadata': metadata,
            'table': sight_img_item_table,
            'class': SigntImgItem
        }
        sight_img_table_dict[p_cityid] = table
        return table


def create_sight_img_item_table_if_not_exist(p_cityid):
    table = SigntImgTables().make_table(p_cityid)
    table['metadata'].create_all(engine)


def add_sight_img_item(p_cityid, p_item):
    table = SigntImgTables().make_table(p_cityid)
    item = table['class'](p_cityid)
    item.sightid = p_item['sightid']
    item.imgid = p_item['imgid']
    item.index = p_item['index']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception, e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def update_sight_img_item(p_cityid, p_item):
    if not (p_cityid and p_item):
        return False
    table = SigntImgTables().make_table(p_cityid)
    try:
        updateField = {
            table['class'].imgid: p_item['imgid']
        }
        session = Session()
        session.query(table['class']).filter(
            table['class'].sightid == p_item['sightid'],
            table['class'].index == p_item['index']).update(updateField, synchronize_session=False)
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def delete_sight_img_item(p_cityid, p_item):
    if not (p_cityid and p_item):
        return False
    table = SigntImgTables().make_table(p_cityid)
    try:
        session = Session()
        session.query(table['class']).filter(
            table['class'].sightid == p_item['sightid'],
            table['class'].index == p_item['index']).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


# batch insert
def add_sight_img_dict(p_cityid, p_dict):
    table = SigntImgTables().make_table(p_cityid)
    res = {'ok': True}
    for p_item in p_dict['imgs']:
        item = table['class'](p_cityid)
        item.sightid = p_dict['sightid']
        item.imgid = p_item['imgid']
        item.index = p_item['index']
        try:
            session = Session()
            session.add(item)
            session.flush()
            session.commit()
            res[p_item['index']] = True
        except Exception, e:
            res[p_item['index']] = False
            res['ok'] = False
            log.exp(e)
            session.rollback()
        finally:
            session.close()
    return res


def get_sight_img_all(p_cityid):
    try:
        session = Session()
        table = SigntImgTables().make_table(p_cityid)
        items = session.query(table['class']).filter_by().all()
        imgid_list = []
        sightid_dict = {}
        res_raw = {}
        for item in items:
            if not res_raw.has_key(item.sightid):
                res_raw[item.sightid] = {'imgs': []}
            res_raw[item.sightid]['imgs'].append(item.to_min_dict())
            sightid_dict[item.sightid] = item.sightid
            imgid_list.append(item.imgid)
        res = {
            'imgid_list': imgid_list,
            'sightid_list': sightid_dict.keys(),
            'res': res_raw,
        }
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def get_sight_img_by_sightid(p_cityid, p_sightid):
    try:
        session = Session()
        table = SigntImgTables().make_table(p_cityid)

        items = session.query(table['class']).filter_by(sightid=p_sightid).all()
        imgid_list = []
        res_raw = []
        for item in items:
            res_raw.append(item.to_min_dict())
            imgid_list.append(item.imgid)
        res = {
            'imgid_list': imgid_list,
            'res': res_raw,
        }
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def get_sight_img_by_sightid_index(p_cityid, p_sightid, p_index):
    try:
        session = Session()
        table = SigntImgTables().make_table(p_cityid)

        item = session.query(table['class']).filter_by(sightid=p_sightid, index=p_index).first()
        res = item.to_dict() if item else None

        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


if __name__ == "__main__":
    test_city = 1
    create_sight_img_item_table_if_not_exist(test_city)
    test_item_dict = {
        'sightid': 2,
        'imgs': [
            {
                'imgid': 100000024,
                'index': 0,
            },
            {
                'imgid': 100000025,
                'index': 1,
            },
            {
                'imgid': 100000026,
                'index': 2,
            },
        ],
    }
    # add_sight_img_item(test_city, test_item_0)
    # add_sight_img_item(test_city, test_item_1)
    print add_sight_img_dict(test_city, test_item_dict)
    print get_sight_img_all(test_city)
